/**
 * 路由管理文件
 * author: Wanghui <wangh@ciqtek.com>
 * company: ubiot.cn
 * date: 2019-08-10
 */

import Vue, {Component} from 'vue'
import Router from 'vue-router'
import * as _ from 'lodash'
import { menu, asyncComponents, IMenu } from '@/menu'
import { intercept } from "@/intercept"

Vue.use(Router)

interface IRouter {
  path: string | undefined
  component: Function
  name: string | undefined
  children?: IRouter[],
  id?: number,
  meta: object
}

/**
 * 用于获取固定格式路由组件
 * @param route
 */
const getRoute = (route: IMenu) => {
  return {
    path: route.path,
    name: route.name,
    id: route.id,
    meta: route.meta,
    component: asyncComponents[route.component]
  }
}

/**格式化路由组件 */
const formatRouter = (root: string) => {
  const routeList: IRouter[] = []
  menu
    .filter(item => {
      return item.root === root
    })
    .forEach((item: IMenu, index) => {
      // @ts-ignore
      if ( !item.exact ) return false
      if ( !item.pid ) {
        routeList.push(getRoute(item))
      }
      else {
        let idx = routeList.findIndex(val => {
          return item.pid === val.id
        })
        // 在当前routeList中找不到pid对应的item时，处理
        if ( idx < 0 ) return routeList.push(getRoute(item))
        if ( !routeList[idx].children ) _.assign(routeList[idx], { children: [] })
        // @ts-ignore
        routeList[idx].children.push(getRoute(item))
      }
    })
  return routeList
}
console.log('#router options',formatRouter("manage"))
// @ts-ignore
const router = new Router({
  routes: [
    {
      path: '/',
      redirect: to => {
        return '/manage/home'
      }
    },
    {
      path: '/login',
      component:  () => import(/* webpackChunkName: "login" */ '@/views/login.vue'),
      name: 'login'
    },
    {
      path: '*',
      component: () => import(/* webpackChunkName: "notFound" */ '@/views/notFound.vue'),
      name: '404'
    },
    {
      path: '/manage',
      component: () => import(/* webpackChunkName: "manage" */ '@/views/Manage.vue'),
      name: 'manage',
      children: formatRouter("manage")
    },
    {
      path: '/service',
      component: () => import(/* webpackChunkName: "service" */ '@/views/Service.vue'),
      name: 'service',
      children: formatRouter("service")
    }
  ]
})

/**
 * 路由拦截
 */
intercept(router)

export default router
